/*
 * 信息填写 
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_auth/common/service.dart';
import 'package:flutter_auth/common/picker_tool.dart';
import 'package:flutter_auth/constant/globals.dart' as globals;
import 'package:flutter_auth/constants.dart';

class EditInfo extends StatefulWidget {
  final value;
  EditInfo({Key key, @required this.value}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    return _editInfoState();
  }
}

/*
 * 定义对象集合 
 */
class JuData {
  String task, content, completionDate, schedule, projectName;
  num projectType, index;
}

class _editInfoState extends State<EditInfo> {
  var userInfo = globals.userInfo['data'];
  // 焦点
  FocusNode _focusNodeTask = new FocusNode(); // 对应任务
  FocusNode _focusNodeContent = new FocusNode(); // 具体事项
  FocusNode _focusNodeProjectInput = new FocusNode(); // 投入项目
  FocusNode _focusNodeCompleteSchedule = new FocusNode(); // 完成进度
  FocusNode _focusNodeCompleteTime = new FocusNode(); // 完成时间
  // 对应任务
  TextEditingController _taskController = new TextEditingController();
  // 具体事项
  TextEditingController _contentController = new TextEditingController();
  // 投入项目
  TextEditingController _projectInputController = new TextEditingController();
  // 完成进度
  TextEditingController _completeScheduleController =
      new TextEditingController();
  // 完成时间
  TextEditingController _completeTimeController = new TextEditingController();
  final _formKey = GlobalKey<FormState>();
  bool _isClearTask = false; //是否显示对应任务清除按钮
  bool _isClearContent = false; // 是否显示对应任务清除按钮
  bool _isClearProInput = false; // 是否显示投入项目清除按钮
  bool _isDeleteProInput = false; // 是否点击了删除按钮
  String proName = ''; // 已经选择的项目名称
  var proList = []; // 所有项目列表
  var proNameList = []; // 任务项目列表
  num proIndex = -1; // 选择的项目索引
  String dayTime = ''; // 完成时间
  var juData = new JuData();
  @override
  void initState() {
    initValue(); // 初始化值
    // 监听对应任务
    _taskController.addListener(() {
      if (_taskController.text.length > 0) {
        _isClearTask = true;
      } else {
        _isClearTask = false;
      }
      setState(() {});
    });
    // 监听具体事项
    _contentController.addListener(() {
      if (_contentController.text.length > 0) {
        _isClearContent = true;
      } else {
        _isClearContent = false;
      }
      setState(() {});
    });
    // 监听投入项目
    _projectInputController.addListener(() {
      if (_projectInputController.text.length > 0) {
        _isClearProInput = true;
      } else {
        _isClearProInput = false;
      }
      setState(() {});
    });
    /*
     * 监听投入项目
     */
    _focusNodeProjectInput.addListener(() {
      if (_focusNodeProjectInput.hasFocus && !_isDeleteProInput) {
        _focusNodeProjectInput.unfocus();
        PickerTool.showStringPicker(
          context,
          normalIndex: proIndex,
          data: proNameList,
          clickCallBack: (int index, var str) {
            setState(() {
              proIndex = index;
              _projectInputController.text = str;
              juData.projectType = proList[proIndex]['id'];
              juData.projectName = proList[proIndex]['name'];
            });
          },
        );
      }
      if (_isDeleteProInput) {
        _focusNodeProjectInput.unfocus();
        _isDeleteProInput = false;
      }
      setState(() {});
    });
    /*
     * 监听完成时间 
     */
    _focusNodeCompleteTime.addListener(() {
      if (_focusNodeCompleteTime.hasFocus) {
        _focusNodeCompleteTime.unfocus();
        PickerTool.showDatePicker(
          context,
          dateType: DateType.YMD,
          title: "日期",
          value:
              dayTime != '' ? DateTime.parse("$dayTime") : new DateTime.now(),
          clickCallback: (var str, var time) {
            setState(() {
              dayTime = str;
              _completeTimeController.text = str;
              juData.completionDate = dayTime;
            });
          },
        );
      }
      setState(() {});
    });
    getProDictionaryList(); // 获取所有项目列表
    super.initState();
  }

  /*
   * 初始化值 
   */
  void initValue() {
    if (widget.value != null) {
      _taskController.text = widget.value['task'];
      _contentController.text = widget.value['content'];
      _projectInputController.text = widget.value['projectName'];
      _completeScheduleController.text = widget.value['schedule'].toString();
      _completeTimeController.text = widget.value['completionDate'];
      dayTime = widget.value['completionDate'];
      juData.task = widget.value['task'];
      juData.content = widget.value['content'];
      juData.completionDate = widget.value['completionDate'];
      juData.schedule = widget.value['schedule'].toString();
      juData.projectName = widget.value['projectName'];
      juData.projectType = widget.value['projectType'];
      juData.index = widget.value['index'];
    }
  }

  /*
   * 获取所有项目列表
   */
  void getProDictionaryList() async {
    List<dynamic> newList =
        await getProDictionary({'userId': userInfo['id']}).then((result) {
      if (result['state'] == true && result['data'].length > 0) {
        return result['data'];
      } else {
        return [];
      }
    });
    setState(() {
      proNameList = newList.map((e) => e['name']).toList();
      proList = newList;
      if (juData.projectType != null) {
        int index =
            newList.indexWhere((item) => item['id'] == juData.projectType);
        proIndex = index;
      }
    });
  }

  @override
  void dispose() {
    // 移除焦点监听
    _taskController.dispose();
    _contentController.dispose();
    _projectInputController.dispose();
    _completeTimeController.dispose();
    _completeScheduleController.dispose();
    super.dispose();
  }

  // 监听焦点
  Future _focusNodeListener() async {}

  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // 输入文本框区域
    Widget inputTextArea = new Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      decoration: new BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white),
      child: new Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _taskWidget(), // 对应任务
            new SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            _contentWidget(), // 具体事项
            new SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            _projectInput(), // 项目投入
            new SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            _schedule(), // 完成进度
            new SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            _completeTime(), // 完成时间
            new SizedBox(
              height: ScreenUtil().setHeight(20),
            ),
            _saveWidget() // 保存
          ],
        ),
      ),
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('日志填写'),
      ),
      backgroundColor: Colors.white,
      // 外层添加一个手势，用于点击空白部分，回收键盘
      body: new GestureDetector(
        onTap: () {
          _focusNodeTask.unfocus();
          _focusNodeContent.unfocus();
          _focusNodeProjectInput.unfocus();
          _focusNodeCompleteSchedule.unfocus();
          _focusNodeCompleteTime.unfocus();
        },
        child: new ListView(
          children: [
            inputTextArea,
            new SizedBox(
              height: ScreenUtil().setHeight(80),
            ),
          ],
        ),
      ),
    );
  }

  /*
   * 对应任务 
   */
  Widget _taskWidget() {
    return TextFormField(
      maxLines: 2,
      maxLength: 500,
      keyboardType: TextInputType.multiline,
      controller: _taskController,
      focusNode: _focusNodeTask,
      //设置键盘类型
      decoration: InputDecoration(
        labelText: "对应任务",
        suffixIcon: (_isClearTask)
            ? IconButton(
                icon: Icon(Icons.clear),
                onPressed: () {
                  // 清空输入框内容
                  _taskController.clear();
                },
              )
            : null,
      ),
      //验证对应任务
      validator: (v) {
        return v.trim().length > 0 ? null : "对应任务不能为空";
      },
      onChanged: (String value) {
        setState(() {
          juData.task = value;
        });
      },
    );
  }

  /*
   * 具体事项 
   */
  Widget _contentWidget() {
    return Card(
      child: Padding(
        padding: EdgeInsets.all(8.0),
        child: TextFormField(
          maxLines: 5,
          maxLength: 500,
          keyboardType: TextInputType.multiline,
          controller: _contentController,
          focusNode: _focusNodeContent,
          //设置键盘类型
          decoration: InputDecoration(
            labelText: "具体事项",
            suffixIcon: (_isClearContent)
                ? IconButton(
                    icon: Icon(Icons.clear),
                    onPressed: () {
                      // 清空输入框内容
                      _contentController.clear();
                    },
                  )
                : null,
          ),
          //验证对应任务
          validator: (v) {
            return v.trim().length > 0 ? null : "具体事项不能为空";
          },
          onChanged: (String value) {
            setState(() {
              juData.content = value;
            });
          },
        ),
      ),
    );
  }

  /*
   * 项目投入
   */
  Widget _projectInput() {
    return TextFormField(
      keyboardType: TextInputType.multiline,
      controller: _projectInputController,
      focusNode: _focusNodeProjectInput,
      //设置键盘类型
      decoration: InputDecoration(
        labelText: "投入项目",
        suffixIcon: (_isClearProInput)
            ? IconButton(
                icon: Icon(Icons.delete),
                onPressed: () {
                  _projectInputController.clear();
                  _isDeleteProInput = true;
                  setState(() {
                    proIndex = -1;
                  });
                },
              )
            : null,
      ),
      //验证对应任务
      validator: (v) {
        return v.trim().length > 0 ? null : "投入项目不能为空";
      },
    );
  }

  /*
   * 完成进度
   */
  Widget _schedule() {
    return TextFormField(
      keyboardType: TextInputType.number,
      controller: _completeScheduleController,
      focusNode: _focusNodeCompleteSchedule,
      //设置键盘类型
      decoration: InputDecoration(
        labelText: "完成进度（%）",
      ),
      //验证对应任务
      validator: (v) {
        return v.trim().length > 0 ? null : "完成进度不能为空";
      },
      onChanged: (String value) {
        if (num.parse(value) >= 100) {
          _completeScheduleController.text = '100';
        }
        if (num.parse(value) <= 0) {
          _completeScheduleController.text = '0';
        }
        setState(() {
          juData.schedule = _completeScheduleController.text;
        });
      },
    );
  }

  /*
   * 完成时间 
   */
  Widget _completeTime() {
    return TextFormField(
      keyboardType: TextInputType.number,
      controller: _completeTimeController,
      focusNode: _focusNodeCompleteTime,
      //设置键盘类型
      decoration: InputDecoration(
        labelText: "完成时间",
      ),
      //验证对应任务
      validator: (v) {
        return v.trim().length > 0 ? null : "完成时间不能为空";
      },
    );
  }

  /*
   * 保存 
   */
  Widget _saveWidget() {
    return Container(
      margin: EdgeInsets.all(10.0), //容器外补白
      alignment: Alignment.center,
      child: SizedBox(
        width: 400,
        height: 60,
        child: RaisedButton.icon(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(4),
          ),
          icon: Icon(
            Icons.save,
            color: Colors.white,
          ),
          color: kPrimaryColor,
          label: Text(
            "保存",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18.0,
              height: 1.2,
            ),
          ),
          onPressed: () {
            // 点击登录按钮，解除焦点，回收键盘
            _focusNodeTask.unfocus();
            _focusNodeContent.unfocus();
            _focusNodeCompleteSchedule.unfocus();
            if (_formKey.currentState.validate()) {
              Navigator.pop(context, juData);
            }
          },
        ),
      ),
    );
  }
}
